unit uLangSelectForm;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ComCtrls, ImgList;

type
  TfmLangSelect = class(TForm)
    cbLanguage: TComboBoxEx;
    Label1: TLabel;
    Button1: TButton;
    ilFlags: TImageList;
  private
    { Private declarations }
    FLangList: TStringList;
  public
    { Public declarations }
    procedure AfterConstruction; override;
    procedure BeforeDestruction; override;

    class function Invoke: string;
  end;

var
  fmLangSelect: TfmLangSelect;

implementation

{$R *.dfm}

uses uBaseCalcForm, uLocalization, uConfig;

procedure TfmLangSelect.AfterConstruction;
  function LoadFlag(ALocale: string): integer;
  var ic: TIcon;
  begin
    Result := -1;
    if FileExists(AppDir+'Data\'+ALocale+'.ico') then try
      ic := TIcon.Create;
      try
        ic.LoadFromFile(AppDir+'Data\'+ALocale+'.ico');
        Result := ilFlags.AddIcon(ic);
      finally ic.Free; end;
    except end;
  end;

var sr: TSearchRec;
    s,def: string;
    idx: integer;
begin
  inherited;
  FLangList := TStringList.Create;

  def := Config.AsString['main.language', ''];
  if (def='') then def := 'en-US';

  idx := -1;

  if FindFirst(AppDir+'Data\*.lcxml', faAnyFile, sr) = 0 then begin
    repeat
      with TLocaleFile.Create do try
        Load(AppDir+'Data\'+sr.Name);
        s := LocaleName;
        if (s<>'') then
          with cbLanguage.ItemsEx.Add do begin
            Caption := s;
            ImageIndex := LoadFlag(LocaleStr);
            if SameText(LocaleStr, def) then idx := Index;
            FLangList.Add(LocaleStr);
          end;
      finally Free; end;
    until FindNext(sr)<>0;
    FindClose(sr);
  end;
  if (idx>-1) then cbLanguage.ItemIndex := idx;
end;

procedure TfmLangSelect.BeforeDestruction;
begin
  FLangList.Free;
  inherited;
end;

class function TfmLangSelect.Invoke: string;
begin
  Result := 'en-US';

  with Self.Create(Application) do try
    ShowModal;
    if (cbLanguage.ItemIndex<>-1) then
      Result := FLangList[cbLanguage.ItemIndex];
  finally Free; end;
end;

end.
